import requests
from django.utils.text import slugify
from django.shortcuts import get_object_or_404
from django.shortcuts import render
from django.core.files.base import ContentFile
from django.shortcuts import redirect
from transliterate import translit
from transliterate.exceptions import LanguageDetectionError
from django.contrib.auth.models import User

from . import models
from . import forms
from . import utils


def get_image_name(title, url):

    """ Получаем имя для изображения """

    print(f'image_titleee - {title}')
    try:
        title = translit(title, reversed=True)
        image_name = '{}.{}'.format(
                                slugify(title),
                                url.split('.')[-1].lower())
        return image_name

    except LanguageDetectionError as error:

        image_name = '{}.{}'.format(
                                slugify(title),
                                url.split('.')[-1].lower())
 
        return image_name


def download_image(link):

    """ Скачиваем изображение """

    response = requests.get(link)
    content = response.content

    return content


def get_slug(title):

    """ Получаем slug """

    try:
        slug = slugify(translit(title, reversed=True))
        print(f'slug - {slug}')
        return slug

    except LanguageDetectionError as error:
        print(error)
        return slugify(title)


class ObjectDetailMixin:

    model = None
    form = None

    def post(self, request, slug):

        if self.form.__name__ == 'ImageUpdateForm':

            image = self.model.objects.get(slug=slug)
            bound_form = self.form(request.POST, request.FILES, instance=image)

        if self.form.__name__ == 'ImageCreateForm':

            bound_form = forms.ImageCreateForm(request.POST)

        if bound_form.is_valid():

            cd = bound_form.cleaned_data
            new_image = bound_form.save(commit=False)

            new_image.user=request.user
            new_image.title=cd['title']
            new_image.slug=get_slug(cd['title'])
            new_image.url=cd['url']
            new_image.image.save(get_image_name(cd['title'], cd['url']), ContentFile(download_image(cd['url'])))
            new_image.description=cd['description']
            new_image.save()

            return redirect('images:show_image', slug=new_image.slug)

        else:

            context = {'section': 'images', 'form': bound_form, 'slug': slug}
            print(f'errors - {bound_form.errors}')
            return render(request, 'images/create.html', context)


def get_image_extension(url):

    """ Получаем расширение изображения """

    valid_extensions = ['.jpg', '.jpeg', '.png']
    extension = [extension for extension in valid_extensions if extension in url]

    if extension: return extension[0]
    else: return False
